package org.zjx.swing.view;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;

public class MenuView extends JFrame {
    private JPanel buttonPanel;
    private JLabel backgroundLabel;

    public MenuView() {
        setTitle("工具选择界面");
        setSize(600, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        backgroundLabel = new JLabel();
        backgroundLabel.setLayout(new BorderLayout());


        // 设置按钮面板
        buttonPanel = new JPanel();
        buttonPanel.setOpaque(false);
        buttonPanel.setBorder(new EmptyBorder(10, 10, 50, 10));
        buttonPanel.setLayout(new GridBagLayout());

        add(backgroundLabel);
    }

    public void setBackground(BufferedImage image) {
        // 缩放背景图片
        Image scaledImage = image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
        ImageIcon backgroundIcon = new ImageIcon(scaledImage);
        backgroundLabel.setIcon(backgroundIcon);
    }

    public void setButtonList(String[] buttonNames){
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 创建按钮
        for (int i = 0; i < buttonNames.length; i++) {
            JButton button = new JButton(buttonNames[i]);
            button.setPreferredSize(new Dimension(120, 50));
            button.setFont(new Font("宋体", Font.BOLD, 18));
            button.setBackground(new Color(173, 216, 230));
            button.setFocusPainted(false);

            gbc.gridx = i % 2;
            gbc.gridy = i / 2;
            buttonPanel.add(button, gbc);
        }
        backgroundLabel.add(buttonPanel, BorderLayout.CENTER);
    }

    public void addButtonListener(ActionListener listener) {
        for (Component comp : buttonPanel.getComponents()) {
            if (comp instanceof JButton) {
                ((JButton) comp).addActionListener(listener);
            }
        }
    }
}